package com.ruoyi.web.controller.epidemic;

import cn.hutool.json.JSONUtil;
import com.ruoyi.epidemic.domain.*;
import com.ruoyi.epidemic.service.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@RestController
@RequestMapping("/wxCp/push")
@Slf4j
public class WxCpPushController {

    @Value("${wechat.cp.corpId}")
    private String corpId;

    @Value("${wechat.cp.appConfigs.agentId}")
    private Integer agentId;

    @Value("${wechat.cp.appConfigs.corpSecret}")
    private String corpsecret;

    @Value("${wechat.cp.appConfigs.token}")
    private String token;

    @Value("${wechat.cp.appConfigs.aesKey}")
    private String aesKey;

    @Autowired
    private IWxCpUserService wxCpUserService;

    @Autowired
    private IWxCpDepartService wxCpDepartService;

    @Autowired
    private IWxCpSysUserService wxCpSysUserService;

    @Autowired
    private IWxCpSysDeptService wxCpSysDeptService;

    @Autowired
    private ISysUserDeptService sysUserDeptService;


    @GetMapping(value = "/changeContact", produces = "text/plain;charset=utf-8")
    public String authGet(//@PathVariable Integer agentId,
                          @RequestParam(name = "msg_signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpId(corpId);      // 设置微信企业号的appid
        config.setCorpSecret(corpsecret);  // 设置微信企业号的app corpSecret
        config.setAgentId(agentId);
        config.setToken(token);
        config.setAesKey(aesKey);
        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
//    final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }

        if (wxCpService.checkSignature(signature, timestamp, nonce, echostr)) {
            log.info(new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr));
            return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr);
        }

        return "非法请求";
    }

    @PostMapping(value = "/changeContact", produces = "application/xml; charset=UTF-8")
    public String post(//@PathVariable Integer agentId,
                       @RequestBody String requestBody,
                       @RequestParam("msg_signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                signature, timestamp, nonce, requestBody);

//    final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpId(corpId);      // 设置微信企业号的appid
        config.setCorpSecret(corpsecret);  // 设置微信企业号的app corpSecret
        config.setAgentId(agentId);
        config.setToken(token);
        config.setAesKey(aesKey);
        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
        WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(),
                timestamp, nonce, signature);
        log.info("\n消息解密后内容为：\n{} ", JSONUtil.toJsonStr(inMessage));
        String event = inMessage.getEvent();
        String changeType= inMessage.getChangeType();
        String userId = inMessage.getUserId();
        String newUserId = StringUtils.isEmpty(inMessage.getNewUserId()) ? userId : inMessage.getNewUserId() ;
        String name = inMessage.getName();
        Long[] departments = inMessage.getDepartments();
        String departId = inMessage.getId();
        String parentId = inMessage.getParentId();
        String order = inMessage.getOrder();
        String status = inMessage.getStatus();
        status = "1".equals(status) ? "0" : "1";

        //联系人变更
        if("change_contact".equals(event)){
            handleChangeContact(changeType, userId, newUserId, name, departments, departId, parentId, order, status);
        }
        return null;
    }

    //联系人变更处理
    public void handleChangeContact(String changeType, String userId, String newUserId, String name,
                                    Long[] departments, String departId, String parentId, String order, String status){

        //新增成员事件
        if("create_user".equals(changeType)){
            //企业微信人员
            WxCpUser wxCpUser = new WxCpUser();
            wxCpUser.setUserId(userId);
            wxCpUser.setDeptIds(JSONUtil.toJsonStr(departments));
            wxCpUser.setLoginName(name);
            wxCpUser.setUserName(name);
            wxCpUser.setDelFlag("0");
            wxCpUser.setStatus(status);

            //企业微信-系统人员
            WxCpSysUser wxCpSysUser = new WxCpSysUser();
            wxCpSysUser.setUserId(userId);
            wxCpSysUser.setLoginName(name);
            wxCpSysUser.setUserName(name);
            wxCpSysUser.setDelFlag("0");
            wxCpSysUser.setStatus(status);

            //企业微信人员-部门列表
            List<SysUserDept> sysUserDeptList = new ArrayList<SysUserDept>();
            if(null != departments && departments.length >0){
                for(Long departmentId : departments){
                    //企业微信系统人员-部门
                    SysUserDept sysUserDept = new SysUserDept();
                    sysUserDept.setUserId(userId);
                    sysUserDept.setDeptId(departmentId);
                    sysUserDeptList.add(sysUserDept);
                }
            }

            hanleCreateUser(wxCpUser, wxCpSysUser, sysUserDeptList);
            log.info("===========完成新增成员事件处理=========");
        }
        //更新成员事件
        if("update_user".equals(changeType)){
            hanleUpdateUser(userId, newUserId, name, departments, status);
            log.info("===========完成更新成员事件处理=========");
        }
        //删除成员事件
        if("delete_user".equals(changeType)){
            hanleDeleteUser(userId);
            log.info("===========完成删除成员事件处理=========");
        }
        //新增部门事件
        if("create_party".equals(changeType)){

            //企业微信部门
            WxCpDepart wxCpDepart = new WxCpDepart();
            wxCpDepart.setDeptId(Long.getLong(departId));
            wxCpDepart.setDeptName(name);
            wxCpDepart.setParentId(Long.getLong(parentId));
            wxCpDepart.setOrderNum(Long.getLong(order));
            wxCpDepart.setDelFlag("0");

            //企业微信-系统部门
            WxCpSysDept wxCpSysDept = new WxCpSysDept();
            wxCpSysDept.setDeptId(Long.getLong(departId));
            wxCpSysDept.setDeptName(name);
            wxCpSysDept.setParentId(Long.getLong(parentId));
            wxCpSysDept.setOrderNum(Long.getLong(order));
            wxCpSysDept.setDelFlag("0");
            hanleCreateParty(wxCpDepart, wxCpSysDept);
            log.info("===========完成新增部门事件处理=========");
        }
        //更新部门事件
        if("update_party".equals(changeType)){
            //企业微信部门
            WxCpDepart wxCpDepart = new WxCpDepart();
            wxCpDepart.setDeptId(Long.getLong(departId));
            wxCpDepart.setDeptName(name);
            wxCpDepart.setParentId(Long.getLong(parentId));

            //企业微信-系统部门
            WxCpSysDept wxCpSysDept = new WxCpSysDept();
            wxCpSysDept.setDeptId(Long.getLong(departId));
            wxCpSysDept.setDeptName(name);
            wxCpSysDept.setParentId(Long.getLong(parentId));
            hanleUpdateParty(wxCpDepart, wxCpSysDept);
            log.info("===========更新新增部门事件处理=========");
        }
        //删除部门事件
        if("delete_party".equals(changeType)){
            hanleDeleteParty(Long.getLong(departId));
            log.info("===========完成删除部门事件处理=========");
        }

    }

    /**
     * 新增成员事件
     * @param wxCpUser
     * @param wxCpSysUser
     * @param sysUserDeptList
     */
    public void hanleCreateUser(WxCpUser wxCpUser, WxCpSysUser wxCpSysUser, List<SysUserDept> sysUserDeptList){

        wxCpUserService.replaceWxCpUser(wxCpUser);
        wxCpSysUserService.replaceWxCpSysUser(wxCpSysUser);
        for(SysUserDept sysUserDept : sysUserDeptList){
            sysUserDeptService.replaceSysUserDept(sysUserDept);
        }
    }

    /**
     * 更新成员事件
     * @param userId
     * @param newUserId
     * @param name
     * @param departments
     */
    public void hanleUpdateUser(String userId, String newUserId, String name,
                                Long[] departments, String status){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId",userId);
        params.put("newUserId",newUserId);
        params.put("loginName", name);
        params.put("userName", name);
        params.put("status", status);

        //更新WxCpUser
        Map<String, Object> wxCpUserParams = params;
        wxCpUserParams.put("deptIds", JSONUtil.toJsonStr(departments));
        wxCpUserService.updateWxCpUserByMap(wxCpUserParams);

        //更新WxCpSysUser
        wxCpSysUserService.updateWxCpSysUserByMap(params);

        //更新SysUserDept
        if(null != departments && departments.length >0) {
            sysUserDeptService.deleteSysUserDeptByUserId(userId);
            for (Long deptId : departments) {
                //企业微信系统人员-部门
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setUserId(userId);
                sysUserDept.setDeptId(deptId);
                sysUserDeptService.insertSysUserDept(sysUserDept);
            }
        }

    }

    /**
     * 删除成员事件
     * @param userId
     */
    public void hanleDeleteUser(String userId ){

        wxCpUserService.deleteWxCpUserByUserId(userId);
        wxCpSysUserService.deleteWxCpSysUserByUserId(userId);
        sysUserDeptService.deleteSysUserDeptByUserId(userId);
    }

    /**
     * 新增部门事件
     * @param wxCpDepart
     * @param wxCpSysDept
     */
    public void hanleCreateParty(WxCpDepart wxCpDepart, WxCpSysDept wxCpSysDept){
        wxCpDepartService.insertWxCpDepart(wxCpDepart);
        wxCpSysDeptService.insertWxCpSysDept(wxCpSysDept);
    }

    /**
     * 更新部门事件
     * @param wxCpDepart
     * @param wxCpSysDept
     */
    public void hanleUpdateParty(WxCpDepart wxCpDepart ,WxCpSysDept wxCpSysDept){

        wxCpDepartService.updateWxCpDepart(wxCpDepart);
        wxCpSysDeptService.updateWxCpSysDept(wxCpSysDept);
    }

    /**
     * 删除部门事件
     * @param deptId
     */
    public void hanleDeleteParty(Long deptId){

        wxCpDepartService.deleteWxCpDepartByDeptId(deptId);
        wxCpSysDeptService.deleteWxCpSysDeptByDeptId(deptId);
    }


//  private WxCpXmlOutMessage route(Integer agentId, WxCpXmlMessage message) {
//    try {
//      return WxCpConfiguration.getRouters().get(agentId).route(message);
//    } catch (Exception e) {
//      this.logger.error(e.getMessage(), e);
//    }
//
//    return null;
//  }


}
